import {
  _decorator,
  Component,
  TiledMap,
  RigidBody,
  v2,
  Node,
  BoxCollider,
  ERigidBodyType,
  director,
  PhysicsSystem2D,
  BoxCollider2D,
  PhysicsSystem,
  Vec2,
  TiledObjectGroup,
  UITransform,
} from 'cc'
const { ccclass, property } = _decorator

@ccclass('TiledMapCtrl')
export class TiledMapCtrl extends Component {

  onLoad() {
    PhysicsSystem2D.instance.enable = true
    this.initMap(this.node)
  }

  initMap(mapNode: Node) {
    console.log(mapNode);
    let tiledMap = mapNode.getComponent(TiledMap)
    let tiledSize = tiledMap.getTileSize()
    let layer = tiledMap.getLayer('ObjectLayer')
    let layers = tiledMap.getObjectGroup('PlayerLayer')
    let layerSize = layer.getLayerSize()
    let transform = mapNode.getComponent(UITransform)
    let h = transform.height / 2
    let w = transform.width / 2

    let mapData = []

    for (let i = 0; i < layerSize.width; i++) {
      mapData[i] = []
      for (let j = 0; j < layerSize.height; j++) {
        let gid = layer.getTileGIDAt(i, j)
        mapData[i].push(gid)
        if (gid != 0) {
          // let tiled = layer.getTiledTileAt(i, j, false)
          let pos = layer.getPositionAt(i, j)
          let tiled = new Node(`Collider-${gid}`)
          console.log(pos);
          tiled.setPosition(pos.x - w, pos.y - h) 
          let collider = tiled.addComponent(BoxCollider2D)
          collider.group = 2
          collider.offset = v2(tiledSize.width / 2, tiledSize.height / 2)
          collider.size = tiledSize
          collider.apply()
          tiled.addComponent('WallCtrl')
          layers.node.addChild(tiled)
        }
        
        
        // let tiled = layer.getTiledTileAt(i, j, true)
        // if (tiled.grid != 0) {
        //   // tiled.node.group = 'WALL'
        //   // let body = tiled.node.addComponent(RigidBody)
        //   // body.type = ERigidBodyType.STATIC
        //   let collider = tiled.node.addComponent(BoxCollider2D)
        //   collider.group = 1
        //   collider.offset = v2(tiledSize.width / 2, tiledSize.height / 2)
        //   collider.size = tiledSize
        //   console.log(collider);
        //   collider.apply()
        // }
      }
    }
    console.log(mapData);
  }
}
